﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using Microsoft.Cmp.InsertMailService;
using Microsoft.SisparkSaaS.DAL.Common;
using Microsoft.Cmp.Framework;

namespace InsertMailService
{
    public partial class InsertMailService : ServiceBase
    {
        private Thread _thread = null;
        public InsertMailService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            _thread = new Thread(SendMail);
            _thread.Start();
        }

        protected override void OnStop()
        {
            Log.Info("OnStop", "运行添加邮件服务结束。");
        }
        public void Start(string[] args)
        {
            OnStart(args);
        }
        private static void SendMail()
        {
            Log.Info("OnStart", "开始运行添加邮件服务。");
            string sendMailStartDay = ConfigurationManager.AppSettings["SendMailStartDay"].ToString();
            string ThreadSleep = ConfigurationManager.AppSettings["ThreadSleepTime"].ToString();
           
            while (true)
            {
                var insertstatus = false;
                var sendMailStartDays = sendMailStartDay.Split(',');
                foreach (string sendday in sendMailStartDays)
                {
                    if(!string.IsNullOrEmpty(sendday)&&sendday==DateTime.Today.Day.ToString(CultureInfo.InvariantCulture))
                    {
                        insertstatus = true;
                    }
                }
                if (insertstatus)
                {

                    try
                    {
                        var sendEMail = new InsertMail(new WSBO_SendNoticeEmailDAL());
                        sendEMail.Execute();
                    }
                    catch (Exception ex)
                    {
                        //记录Windows异常
                        Log.Error("发送邮件服务异常",
                                  string.Format("错误描述：{0}，堆栈信息：{1}", ex.Message, ex.StackTrace),
                                  string.Empty,
                                  TraceEventType.Error);
                    }

                    Thread.Sleep(int.Parse(ThreadSleep));
                }
                else
                {
                    Log.Info("OnStart", "不在运行时间段内，休眠24小时。");
                    Thread.Sleep(int.Parse(ThreadSleep));
                }
            }
        }
    }
}
